﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Discuz.Toolkit;
using LY.Common;
using LY.Common.Utils;
using LY.Entity;
using LY.Entity.Jsons;
using LY.Interface;
using QJ.CMS.Filters;

namespace QJ.CMS.Controllers
{

    /// <summary>
    ///用户登陆注册模块
    /// </summary>
    public class LoginController : Controller
    {
        private readonly ISiteconfigService _siteconfigService;
        private ISysTemplateService _templateService;
        private IMemberService _memberService;
        private IBankCardService _bankCardService;
        private IReferralsService _referrals;
        private IScoreService _scoreService;
        private readonly IMemberLogService _memberLogService;

        public LoginController(IMemberService memberService, IBankCardService bankCardService, IReferralsService referrals, IMemberLogService memberLogService, IScoreService scoreService, ISiteconfigService siteconfigService, ISysTemplateService templateService)
        {
            _memberService = memberService;
            _bankCardService = bankCardService;
            _referrals = referrals;
            _memberLogService = memberLogService;
            _scoreService = scoreService;
            _siteconfigService = siteconfigService;
            _templateService = templateService;
        }

        #region 注册 登陆
        [MyAuthorization(IsLoginValidate = "retrurnUrl")]
        public ActionResult Index()
        {
            if (Request["retrurnUrl"] != null)
            {
                return Redirect(Server.UrlDecode(Request["retrurnUrl"]));
            }
            return View();
        }

        [MyAuthorization]
        public ActionResult ISLogin()
        {
            return View();
        }

        //前台页面的登陆
        [HttpPost]
        public ActionResult Login(string userName, string userPwd, string validateCode)
        {

            return RedirectToAction("Index");
            //先将密码加密
            //string md5Password = MD5Util.GetMD5_32(userPwd);
            //U_Member member = _memberService.login(userName, md5Password);
            //var rMsg = new JsonSMsg();
            //if (validateCode != Session["ValidateCode"].ToString())
            //{
            //    rMsg.Status = -1;
            //    rMsg.Message = "验证码错误";
            //    return Json(rMsg);
            //}
            //if (member != null)
            //{
            //    rMsg.Status = 1;

            //    var aaa = Request.Headers["X-Rewrite-URL"];

            //    if (Request["myurl"] != null)
            //    {
            //        //解码，解决中文乱码的问题。
            //        rMsg.Data = Server.UrlDecode(Request["myurl"]);
            //    }
            //    else
            //    {
            //        rMsg.Data = Url.Action("Index", "Account");
            //    }
            //    Session["CurrentUser"] = member;
            //    Utility.WriteCookie("DTRememberName", member.Name, 14400);
            //    Utility.WriteCookie("AdminName", "DTcms", member.Name);
            //    Utility.WriteCookie("AdminPwd", "DTcms", member.Password);
            //    FormsAuthentication.SetAuthCookie(member.ID.ToString(), false);
            //    SetCookie();


            //    if (ConfigurationManager.AppSettings["OpenBBS"].ToString() == "true")
            //    {
            //        //登陆论坛
            //        DiscuzSession ds = ConformityHandler.InitDiscuzSession();
            //        int DntUid = ds.GetUserID(member.Name);
            //        if (DntUid <= 0)
            //        {
            //            DntUid = ds.Register(member.Name, member.Password, null, true);
            //        }
            //        ds.Login(DntUid, member.Password, true, 100, "");
            //    }


            //    //登陆日志;
            //    var memberLog = new U_MemberLoginLog
            //        {
            //            IP = GetIP(),
            //            LoginTime = DateTime.Now,
            //            MemberID = member.ID,
            //            MemberName = member.Name,
            //            Status = 1,
            //            Remark = GetIpCity()
            //        };
            //    _memberLogService.AddMemberLoginLog(memberLog);


            //    _scoreService.SaveScore("登陆", member.ID);


            //    return Json(rMsg);
            //}
            //else
            //{
            //    rMsg.Status = -1;
            //    rMsg.Message = "用户名或密码错误";
            //    return Json(rMsg);
            //}
        }


        public string GetIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {

                return "";
            }

        }

        public string GetIpCity()
        {
            const string url = "http://pv.sohu.com/cityjson?ie=utf-8";
            return LY.Common.Utility.HttpGet(url);
        }

        public string Getcomments(int id)
        {
            string url = "http://api.duoshuo.com/threads/counts.json?short_name=changerbank&threads=" + id;
            return LY.Common.Utility.HttpGet(url);
        }


        //修改密码
        public ActionResult ChangePwd()
        {
            int id = Convert.ToInt32(Request["Id"]);
            U_Member member = _memberService.GetMember(id);
            return View(member);
        }

        //保存修改的密码
        public ActionResult SavePwd(string oldPwd, string newPwd)
        {
            int id = Convert.ToInt32(Request["Id"]);
            U_Member member = _memberService.GetMember(id);
            if (MD5Util.GetMD5_32(oldPwd) == member.Password)//输入的旧密码与数据库中的相同
            {
                member.Password = MD5Util.GetMD5_32(newPwd);
                _memberService.SaveMember(member);
            }
            return null;
        }

        //前台页面注册
        public ActionResult Register()
        {
            return View();
        }

        //注册保存
        [HttpPost]
        public ActionResult MemberSave(FormCollection formCollection)
        {
            JsonSMsg msg = new JsonSMsg();
            if ((string)Session[RBSKeys.SESSION_SMS_CODE] != formCollection["validateCode"])
            {
                msg.Message = "验证码错误";
                msg.Status = -1;
                return Json(msg);
            }

            U_Member member = new U_Member();
            member.Mobilenumber = formCollection["Mobilenumber"];
            member.Name = "CJ" + member.Mobilenumber.Substring(member.Mobilenumber.Length - 4, 4) + LY.Common.Utility.Number(4);// formCollection["Mobilenumber"];
            member.Nickname = "CJ" + member.Mobilenumber.Substring(member.Mobilenumber.Length - 4, 4) + LY.Common.Utility.Number(4);// formCollection["Mobilenumber"];
            //member.Name = formCollection["userName"];
            member.Birthday = DateTime.Parse("1990-01-01");
            member.Password = MD5Util.GetMD5_32(formCollection["userPwd2"]);
            member.IsPhoneValidate = true; 
            member.ClientSource = "网站";
            member.RegistrationTime = DateTime.Now; 
            member.InputTime = DateTime.Now;
            member.LastLoginTime = DateTime.Now;


            if (ConfigurationManager.AppSettings["OpenBBS"].ToString() == "true")
            {
                Discuz.Toolkit.DiscuzSession ds = ConformityHandler.InitDiscuzSession();
                ds.Register(member.Name, member.Password, member.Mobilenumber + "@changerbank.com", true);
            }

            int ret = 0;
            String REF_LINK_ID = formCollection["MemberId"];
            if (REF_LINK_ID != "")
            {
                try
                {
                    int memberId = Convert.ToInt32(Base64Util.Decrypt(REF_LINK_ID));
                    //根据id查询会员存不存在 存在（属于邀请）不存在（提示邀请码不存在）
                    U_Member _member = _memberService.getMemberInfo(memberId);
                    if (_member != null)
                    {
                        ret = _memberService.SaveMember(member);
                        if (ret > 0)
                        {
                            //注册积分
                            _scoreService.SaveScore("邀请注册", memberId);//邀请用户+
                            U_ScoreSetting scoreSetting = _scoreService.GetScoreSetting("邀请注册");//获取积分规则

                            U_Referrals rLink = new U_Referrals();
                            rLink.MemberId = Convert.ToInt32(memberId);
                            rLink.RefUserid = ret;
                            rLink.RefTime = DateTime.Now;
                            rLink.RefIntegration = scoreSetting.extcredits1;//相应积分
                            //奖励类型
                            rLink.RewardsType = 0;
                            //发放状态
                            rLink.ProvideType = 0;
                            _referrals.InsertReferrals(rLink);

                            msg.Message = "邀请成功";
                            msg.Status = 1;
                            // msg.Data = Url.Action("Index", "Account");


                        }
                        else
                        {
                            msg.Status = -1;
                            msg.Message = "注册失败！";
                            return Json(msg);
                        }
                    }
                    else
                    {
                        msg.Status = -1;
                        msg.Message = "邀请码不存在!";
                        return Json(msg);
                    }
                }
                catch (Exception ex)
                {
                    msg.Status = -1;
                    msg.Message = "邀请码不存在!";
                    return Json(msg);
                }
            }
            else
            {
                ret = _memberService.SaveMember(member);
                msg.Message = "注册成功";
                msg.Status = 1;
                //msg.Data = Url.Action("Index", "Account");
            }
            //注册积分
            _scoreService.SaveScore("注册", ret);

            return Json(msg);
        }

        //检测用户名是否存在
        public ActionResult CheckUserName(string userName)
        {
            return Content(_memberService.CheckUserName(userName));
        }

        //绑定银行卡
        public ActionResult SaveBankCard(string CardNo, string CardName, string BankName)
        {
            U_BankCard bankCard = new U_BankCard();
            bankCard.AddTime = DateTime.Now;
            bankCard.BankName = BankName;
            bankCard.CardName = CardName;
            bankCard.CardNO = CardNo;
            bankCard.MemberId = Convert.ToInt32(Request["Id2"]);
            _bankCardService.BindCard(bankCard);
            return null;
        }


        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        public ActionResult Error(string msg = null)
        {
            return Content(msg);
        }


        public ActionResult Logout()
        {

            var Token = Session["Token"] as string;
            var tokenService = new CBSSO.TokenServiceSoapClient();
            tokenService.ClearToken(Token);
            Session["Token"] = null;
            Session["CurrentUser"] = null;
            Session.RemoveAll();
            Session.Clear();
            FormsAuthentication.SignOut();

            Discuz.Toolkit.DiscuzSession ds = ConformityHandler.InitDiscuzSession();
            ds.Logout("");

            return RedirectToAction("Index", "Default");
        }

        #endregion

        #region 判断cookie
        private void SetCookie()
        {
            HttpCookie cookie = Request.Cookies["recentlybrowsed"];
            if (cookie == null)
            {
                cookie = new HttpCookie("recentlybrowsed");
                cookie.Values.Add("rb1", "0");
                cookie.Values.Add("rb2", "0");
                cookie.Values.Add("rb3", "0");
                Response.AppendCookie(cookie);
            }
        }
        #endregion

        #region  邮箱验证
        //邮箱点击验证
        public ActionResult checkEmail(string MemberId, string Email)
        {
            //解密
            int memberId = Convert.ToInt32(Base64Util.Decrypt(MemberId));
            string email = Base64Util.Decrypt(Email);

            U_Member member = _memberService.getMemberInfo(memberId);
            member.Email = email;
            member.IsEmailValidate = true;
            var ret = _memberService.SaveMember(member);
            if (ret > 0)
            {
                //清空session
                Session["CurrentUser"] = member;
                return RedirectToAction("index", "Account");
            }
            else
            {
                return RedirectToAction("Error", "Default");
            }
        }

        //验证邮箱是否已经注册
        public ActionResult checkUsed(string email)
        {
            var rMsg = new JsonSMsg();
            if (email.Trim() == "")
            {
                rMsg.Status = -1;
                rMsg.Message = "请输入邮箱！";
            }
            else
            {
                U_Member member = _memberService.getMemberStatus(email);
                //可以注册
                if (member == null)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "该邮箱没有被注册，可以使用！";
                }
                else
                {

                    rMsg.Status = -1;
                    rMsg.Message = "该邮箱已经注册，请更换邮箱！";
                    rMsg.Data = "/Account/EmailCertification";

                }
            }

            return Json(rMsg);
        }


        #endregion

        #region 忘记密码
        //忘记密码
        public ActionResult ForgetPassword()
        {
            return View();
        }

        public ActionResult GetMemberInfo(FormCollection formCollection)
        {
            JsonSMsg msg = new JsonSMsg();
            if ((string)Session["ValidateCode"] != formCollection["validateCode"])
            {
                msg.Message = "验证码错误";
                msg.Status = -2;
                return Json(msg);
            }

            //根据输入内容查询用户
            U_Member member = _memberService.ForgetPwd(formCollection["userName"]);
            if (member != null)
            {
                if (member.IsPhoneValidate == true)
                {
                    Session["ForgetPwd"] = member.Mobilenumber;
                }
                else
                {
                    Session["ForgetPwd"] = member.Email;
                }
                //加密
                string md5id = Base64Util.Encrypt(member.ID.ToString());
                msg.Data = "/Login/VerificationIdentity?memberId=" + md5id;
                msg.Status = 1;
            }
            else
            {
                msg.Status = -1;
                msg.Message = "你的账户信息异常，请换种条件找回！";
            }
            return Json(msg);
        }
        //验证身份
        public ActionResult VerificationIdentity(string memberId)
        {
            try
            {
                //解密
                int Id = Convert.ToInt32(Base64Util.Decrypt(memberId));
                U_Member member = _memberService.GetMember(Id);
                if (member != null)
                {
                    if (Session["ForgetPwd"].ToString() == member.Mobilenumber || Session["ForgetPwd"].ToString() == member.Email)
                    {
                        ViewBag.Id = Id;
                        ViewBag.name = member.Name;
                        ViewBag.email = "";
                        ViewBag.phone = "";
                        //  ViewBag.EmailTrue = member.Email;
                        ViewBag.phoneTrue = member.Mobilenumber;
                        if (member.IsEmailValidate == true)
                        {
                            string[] email = member.Email.Split('@');
                            string fastemail = email[0].Substring(0, 2);
                            string endemail = email[0].Substring(email[0].Length - 1, 1);
                            ViewBag.email = fastemail + "......" + endemail + "@" + email[1];
                        }
                        if (member.IsPhoneValidate == true)
                        {
                            ViewBag.phone = member.Mobilenumber.Insert(3, "*****").Remove(8, 5);
                        }

                    }
                    else
                    {
                        return RedirectToAction("Error", "Default");
                    }
                }
                else
                {
                    return RedirectToAction("Error", "Default");
                }
            }
            catch (Exception)
            {

                return RedirectToAction("Error", "Default");
            }


            return View();
        }
        //验证邮箱
        public JsonResult SendEmail(FormCollection form)
        {
            JsonSMsg rMsg = new JsonSMsg();

            var siteconfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath"));
            var config = _siteconfigService.LoadConfig();

            //获取邮件短信模板 模板名字(registerlink)
            var templateModel = _templateService.GetSysTemplate("用户取回密码");
            var mail = new MailMessage();

            //加密
            string md5id = Base64Util.Encrypt(form["Id"]);

            U_Member member = _memberService.GetMember(Convert.ToInt32(form["Id"]));
            var recipient = new[] { "admin@shcmjgs.com", member.Email };
            mail.AddRecipients(recipient);
            mail.From = siteconfig.Emailfrom;
            mail.FromName = Server.HtmlEncode(siteconfig.Emailnickname);
            mail.BodyFormat = MailFormat.HTML;


            //标题
            mail.Subject = templateModel.TemplateName;
            //内容
            string mailContent = templateModel.TemplateContent;
            mailContent = mailContent.Replace("{webname}", siteconfig.Webname);
            mailContent = mailContent.Replace("{weburl}", siteconfig.Weburl);
            mailContent = mailContent.Replace("{webtel}", siteconfig.Webtel);
            mailContent = mailContent.Replace("{username}", "用户名");
            mailContent = mailContent.Replace("{linkurl}", config.Weburl + "/Login/ResetPwd?MemberId=" + md5id);
            mailContent = mailContent.Replace("{valid}", "1");

            mail.Body = mailContent;
            mail.Charset = "gb2312";
            var sp = new SmtpClient { SmtpServer = siteconfig.Emailsmtp };

            sp.Send(mail, siteconfig.Emailusername, siteconfig.Emailpassword);
            rMsg.Status = 1;
            rMsg.Message = "发送成功,请到邮箱进行验证！";
            return Json(rMsg);
        }
        //验证手机号
        public ActionResult phone(FormCollection formCollection)
        {
            JsonSMsg msg = new JsonSMsg();
            if ((string)Session[RBSKeys.SESSION_SMS_CODE] != formCollection["validateCode"])
            {
                msg.Message = "验证码错误!";
                msg.Status = -1;
                return Json(msg);
            }
            else
            {
                msg.Status = 1;
                msg.Message = "验证成功！";
                //加密
                string md5id = Base64Util.Encrypt(formCollection["Id"]);
                msg.Data = "/Login/ResetPwd?MemberId=" + md5id;
            }
            return Json(msg);
        }

        //重置密码界面
        public ActionResult ResetPwd(string MemberId)
        {
            try
            {
                //解密
                int Id = Convert.ToInt32(Base64Util.Decrypt(MemberId));
                U_Member member = _memberService.GetMember(Id);
                if (member != null)
                {
                    if (Session["ForgetPwd"].ToString() == member.Mobilenumber || Session["ForgetPwd"].ToString() == member.Email)
                    {
                        ViewBag.MemberId = Id;
                    }
                    else
                    {
                        return RedirectToAction("Error", "Default");
                    }
                }
                else
                {
                    return RedirectToAction("Error", "Default");
                }
            }
            catch (Exception)
            {

                return RedirectToAction("Error", "Default");
            }
            return View();
        }
        //修改密码的方法
        public ActionResult UpdatePwd(FormCollection form)
        {
            JsonSMsg rMsg = new JsonSMsg();
            int id = Convert.ToInt32(form["Id"]);
            //重置密码前先将密码加密
            string md5Password = MD5Util.GetMD5_32(form["userPwd"]);
            int ret = _memberService.UpdateLoginpwd(id, md5Password);
            if (ret > 0)
            {
                rMsg.Status = 1;
                rMsg.Message = "重置成功";
                rMsg.Data = "/Change/Index";
            }
            else
            {
                rMsg.Status = -1;
                rMsg.Message = "重置失败";
            }
            return Json(rMsg);
        }
        #endregion

    }
    public static class ConformityHandler
    {
        public static string apikey, secret, webserver;
        private static bool IsInitObject = false;
        public static DiscuzSession ds;
        static ConformityHandler()
        {
            if (!IsInitObject)
            {
                apikey = System.Configuration.ConfigurationManager.AppSettings["DNTAPIKey"].ToString();
                secret = System.Configuration.ConfigurationManager.AppSettings["DNTSecert"].ToString();
                webserver = System.Configuration.ConfigurationManager.AppSettings["DNTWebServer"].ToString();
                ds = new DiscuzSession(apikey, secret, webserver);
                IsInitObject = true;
            }
        }
        public static DiscuzSession InitDiscuzSession()
        {
            return ds;
        }
        /// <summary>
        /// 根据SNS登录E-mail创建论坛登录ID
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        public static string CreateDiscuzNTUsername(string Email)
        {
            return Email.Remove(Email.IndexOf("@"));
        }

    }
}
